<template>
  <div>
    <!-- 参照城市展示弹框 -->
    <el-dialog
      :visible.sync="showReferenceCityVisible"
      :modal-append-to-body="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      width="55%"
      :center="true"
      @close="handleCancelShowDialog"
    >
      <el-row class="heigher_table_wrap">
        <el-button
          type="primary"
          @click="handleSetReferenceCity"
          :loading="setReferCityBtnLoading"
          >设置参照城市</el-button
        >
      </el-row>
      <el-table
        :data="showReferenceCityData"
        :header-cell-style="{ textAlign: 'center' }"
        :cell-style="{ textAlign: 'center' }"
        border="border"
        use-virtual
        :height="400"
      >
        <el-table-column
          v-for="column in showReferenceCityColumns"
          :key="column.key"
          :prop="column.key"
          :label="column.title"
          :property="column.key"
          :align="column.align"
          :min-width="column.width || 120"
          :fixed="column.fixed"
          :formatter="column.formatter"
          :show-overflow-tooltip="true"
        >
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleCancelShowDialog">取 消</el-button>
        <el-button
          v-preventReClick
          type="primary"
          @click="handleSubmitReferenceCityList"
          >确定</el-button
        >
      </div>
    </el-dialog>
    <!-- 设置参照城市弹框 -->
    <el-dialog
      :visible.sync="setReferenceCityVisible"
      :modal-append-to-body="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      width="65%"
      :center="true"
      @close="handleCancelSetDialog"
    >
      <el-row class="batch_modify_wrap">
        <el-form label-width="130px">
          <el-row v-if="purchasePriceType === '1'">
            <el-col>
              <el-form-item label="默认参照城市设置:">
                <el-select
                  v-model="defaultReferenceCityUuid"
                  placeholder="请选择"
                  @change="handleSelectDefaultReferCity"
                >
                  <el-option
                    v-for="item in defaultReferenceCityList"
                    :key="item.templateCityUuid"
                    :label="item.templateCityName"
                    :value="item.templateCityUuid"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <div class="row-batch-wrap">
            <el-form-item label="批量输入成本比例:">
              <input-number
                v-model="batchData.costPriceRatio"
                controls-position="right"
              />
            </el-form-item>
            <el-form-item v-if="purchasePriceType !== '1'" label="批量设置参照城市:">
              <el-select
                v-if="referenceCityList.length !== 0"
                v-model="batchData.referenceCityUuid"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in referenceCityList"
                  :disabled="item._disabled"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-button
              class="batch_submit_btn"
              type="primary"
              @click="handleBatchModify"
              >确定</el-button
            >
          </div>
          <el-row>
            <el-col>
              <el-form-item
                label="选择供货城市:"
                label-position="right"
                label-width="100"
              >
                <el-checkbox
                  :indeterminate="isIndeterminate"
                  v-model="isCheckAll"
                  @change="handleCheckAllChange"
                  >全选</el-checkbox
                >
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-row>
      <el-row class="heigher_table_wrap">
        <el-checkbox-group
          v-model="checkedCityCodeList"
          @change="handleCheckedCitiesChange"
        >
          <el-checkbox
            v-for="city in supplyCityList"
            :label="city.cityCode"
            :key="city.cityCode"
            >{{ city.cityName }}</el-checkbox
          >
        </el-checkbox-group>
      </el-row>
      <el-row class="format_table_wrap">
        <reference-city-table
          ref="referenceCityTable"
          :isHandleCheck="isHandleCheck"
          :checkedCityCodeList="checkedCityCodeList"
        >
        </reference-city-table>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleCancelSetDialog">取 消</el-button>
        <el-button
          v-preventReClick
          :loading="submitBtnLoading"
          type="primary"
          @click="handleSetCityListComplete"
          >确定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { ApiRequest } from '@api/basePage';
import referenceCityTable from './referenceCityTable';
import inputNumber from '@/components/inputNumber/inputNumber';
import { mapState, mapMutations } from 'vuex';
import { getCityNamesByPurchaseIneligibleRatio } from '@/utils/getUtils';
export default {
  components: { referenceCityTable, inputNumber },
  props: {
    visible: {
      type: Boolean,
      required: true
    },
    /* 已选择的供应商代码 */
    supplierCode: {
      type: String,
      required: true
    },
    showReferenceCityColumns: {
      type: Array,
      required: true,
      default () {
        return [];
      }
    },
    templateTableData: {
      type: Array,
      default () {
        return [];
      }
    },
    getReferenceCityListAction: {
      type: Function
    },
    getSubmitNoAction: {
      type: Function
    }
  },
  data () {
    return {
      /* 展示参照城市弹框组件data数据 */
      showReferenceCityVisible: this.visible, // 弹框开关
      setReferCityBtnLoading: false, // 弹框表格loading
      showReferenceCityData: [], // 弹框表格数据
      /* 设置参照城市弹框组件data数据 */
      setReferenceCityVisible: false, // 弹框开关
      isIndeterminate: false, // 设置 indeterminate 状态，只负责样式控制
      isCheckAll: false, // 是否全选
      checkedCityCodeList: [], // 已勾选的城市集合
      supplyCityList: [], // 供货城市列表
      batchData: {
        // 批量操作对象
        costPriceRatio: null, // 成本价比例
        referenceCityUuid: '' //  参照城市
      },
      defaultReferenceCityUuid: '', // 默认参照城市uuid
      submitBtnLoading: false,
      isHandleCheck: false, // 手动勾选操作
    };
  },
  computed: {
    ...mapState('commonComps/setReferenceCity', [
      'dataSource', // 设置参照城市表格数据源
      'referenceCityList', // 参照城市下拉列表
      'selectionTableList', // 勾选的参照城市row集合
      'purchasePriceType', // 进价类型 - 统一进价或区域进价
      'defaultReferenceCityList' // 默认参照城市下拉列表
    ])
  },
  watch: {
    /* 监听展示参照城市弹框开关 */
    visible (newValue) {
      this.showReferenceCityVisible = newValue;
    },
    /* 监听是否有参照城市展示页表格数据 */
    templateTableData: {
      handler (val) {
        this.showReferenceCityData = val;
      },
      immediate: true
    }
  },
  methods: {
    ...mapMutations('commonComps/setReferenceCity', [
      'SET_TABLE_DATA',
      'SET_REFERENCE_CITIES',
      'SET_HISTORY_CITY_DATA'
    ]),
    // 没有设置参展关系
    isNotSetReferenceCity () {
      return this.showReferenceCityData.length === 0;
    },
    // 选择默认参照
    handleSelectDefaultReferCity () {
      const cityInfo = this.defaultReferenceCityList.find(item => item.templateCityUuid == this.defaultReferenceCityUuid)
      const defaultCityInfo = { templateCityUuid: cityInfo?.templateCityUuid, templateCityName: cityInfo?.templateCityName }
      const tableData = this.dataSource.map(item => ({ ...item, ...defaultCityInfo }))
      this.SET_TABLE_DATA(tableData)
    },
    /**
      @展示参照城市弹框组件方法
    */
    /* 点击设置参照城市按钮打开设置参照城市弹框 */
    handleSetReferenceCity () {
      this.setReferCityBtnLoading = true;
      this.isHandleCheck = false;
      this.getReferenceCityListAction()
        .then((res) => {
          this.setReferCityBtnLoading = false;
          if (!res) {
            return;
          }
          this.getSupplyCityListAction();
          this.defaultReferenceCityUuid = ''; // 每次进入弹框清空默认参照城市值
          this.setReferenceCityVisible = true;
        })
        .catch(() => {
          this.setReferCityBtnLoading = false;
        });
    },
    /* 提交设置后的参照城市列表给接口 */
    handleSubmitReferenceCityList () {
      if (this.isNotSetReferenceCity()) {
        return this.$message.warning('请设置参照关系');
      }
      let defaultCity = _.find(this.defaultReferenceCityList, (item) => {
        return this.defaultReferenceCityUuid === item.templateCityUuid;
      });
      this.$emit('getSetCityData', { tableData: this.dataSource, defaultCity });
      this.handleCancelShowDialog();
    },
    /* 关闭展示参照城市弹框 */
    handleCancelShowDialog () {
      this.showReferenceCityVisible = false;
      this.$emit('update:visible', this.showReferenceCityVisible);
      this.setReferCityBtnLoading = false;
    },
    /**
      @设置参照城市弹框组件方法
    */
    /* 进入弹框获取供货城市列表 */
    getSupplyCityListAction () {
      let data = { supplierCode: this.supplierCode };
      ApiRequest(
        '/sysback/supplyinfofromsrcm/getSupplyProvinceBySupplyNo',
        'post',
        data,
        true
      )
        .then((res) => {
          if (res.retStatus !== '1') {
            return;
          }
          this.supplyCityList = res.retData;
          this.isCheckAll = true;
          this.handleCheckAllChange(this.isCheckAll); // 默认全选
        })
        .catch((err) => {
          console.log(err);
        });
    },
    /* 批量修改参照城市和成本比例 */
    handleBatchModify () {
      if (this.selectionTableList.length === 0) {
        return this.$message.warning('请勾选列表哦');
      }
      let tableData = _.cloneDeep(this.dataSource);
      let notSupplyCityList = [];
      tableData.forEach((row) => {
        if (row.isSupply === '2') {
          notSupplyCityList.push({
            saleCityUuid: row.saleCityNo,
            templateCityUuid: this.batchData.referenceCityUuid
          });
        }
        let isSelected = _.find(this.selectionTableList, (item) => {
          return (
            item.templateCityUuid === row.templateCityUuid &&
            item.saleCityNo === row.saleCityNo
          );
        });
        if (!isSelected) return false
        if (this.purchasePriceType != '1') {
          const referCity = this.referenceCityList.find(item => this.batchData.referenceCityUuid == item.value)
          row.templateCityUuid = referCity?.value ?? ''
          row.templateCityName = referCity?.label ?? ''
        }
        if (!row.buyPriceRatio) {
          row.buyPriceRatio = 1;
        }
        row.costPriceRatio = this.batchData.costPriceRatio || 1;
      });
      if (!this.batchData.costPriceRatio && notSupplyCityList.length !== 0) {
        this.$refs.referenceCityTable
          .getCostPriceRatioByAreaCodeAction({ notSupplyCityList })
          .then((res) => {
            if (!res) {
              return;
            }
            res.forEach((item) => {
              let index = _.findIndex(tableData, (row) => {
                return item.saleCityUuid === row.saleCityNo;
              });
              tableData[index].buyPriceRatio = item.buyPriceRatio || 1;
              tableData[index].costPriceRatio = item.costPriceRatio;
            });
          });
      }
      this.SET_TABLE_DATA(tableData);
    },
    /* 全选供货城市列表 */
    handleCheckAllChange (val) {
      /**
       * @val 是否全选，true为全选
       */
      let supplyCityCodeList = this.supplyCityList.map((item) => {
        return item.cityCode;
      });
      this.checkedCityCodeList = val ? supplyCityCodeList : [];
      this.isIndeterminate = false;
      if (!val) {
        this.batchData.referenceCityUuid = '';
      }
      this.judgeDefaultCityIsExistFn();
    },
    /* 单选供货城市 */
    handleCheckedCitiesChange (value) {
      this.isHandleCheck = true;
      /**
       * @value 已勾选的供应商城市的code集合
       */
      let checkedCount = value.length;
      this.checkedCityCodeList = value;
      this.isCheckAll = checkedCount === this.supplyCityList.length;
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.supplyCityList.length;
      if (
        !this.checkedCityCodeList.includes(this.batchData.referenceCityUuid)
      ) {
        this.batchData.referenceCityUuid = '';
      }
      this.judgeDefaultCityIsExistFn();
      this.handleSelectDefaultReferCity()
    },
    /* 判断当前勾选供货城市列表是否包含已选默认参照城市，若不包含就清空默认参照城市 */
    judgeDefaultCityIsExistFn () {
      let isExist = this.checkedCityCodeList.includes(
        this.defaultReferenceCityUuid
      );
      if (!isExist) {
        this.defaultReferenceCityUuid = '';
      }
    },
    // 没有设置默认参照城市
    hasNotSetDefaultReferCity () {
      return this.purchasePriceType === '1' && !this.defaultReferenceCityUuid;
    },
    // 有参照城市的值为空
    hasEmptyReferCity (list) {
      return list.some(item => !item.templateCityUuid);
    },
    // 有互相参照的参照城市
    hasReferCityByCrossReference (list) {
      return list.some(row =>
        row.saleCityNo !== row.templateCityUuid &&
        list.findIndex(item => row.saleCityNo === item.templateCityUuid) !== -1
      );
    },
    /* 设置参照城市弹框的提交方法 */
    handleSetCityListComplete () {
      const tableData = _.cloneDeep(this.dataSource).map(item => {
        item.saleAreaUuid = item.areaCode;
        item.saleAreaName = item.areaName;
        return item;
      });
      if (this.hasNotSetDefaultReferCity()) { return this.$message.warning('请设置默认参照城市'); }
      if (this.hasEmptyReferCity(tableData)) { return this.$message.warning('请填写完整参照城市'); }
      if (this.hasReferCityByCrossReference(tableData)) { return this.$message.warning('参照城市之间不能互相参照'); }
      const warnMsgs = getCityNamesByPurchaseIneligibleRatio(tableData);
      if (warnMsgs) { return this.$message.warning(`${warnMsgs}：进价比例和成本价比例均需在0.6-5之间`); }
      this.SET_TABLE_DATA(tableData);
      this.showReferenceCityData = _.cloneDeep(tableData);
      if (this.getSubmitNoAction) {
        this.submitBtnLoading = true;
        this.getSubmitNoAction(tableData).then((res) => {
          this.submitBtnLoading = false;
          if (!res) {
            return false;
          }
          this.$message.success('提交成功');
          this.handleCancelSetDialog();
        });
      } else {
        this.$message.success('提交成功');
        this.handleCancelSetDialog();
      }
    },
    /* 取消操作 */
    handleCancelSetDialog () {
      this.setReferenceCityVisible = false;
      this.$refs.referenceCityTable.$emit('destoryTimerEvent'); // 清除表格组件的定时器
      this.batchData = {
        costPriceRatio: null,
        referenceCityUuid: ''
      };
      // 清空历史参照数据
      this.SET_HISTORY_CITY_DATA([])
    }
  }
};
</script>
<style lang="less" scoped>
.heigher_table_wrap {
  margin-bottom: 15px;
}
.row-batch-wrap {
  display: flex;
  align-items: flex-start;
  .el-form-item {
    margin-right: 10px;
  }
}
</style>
